from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .serializer import *
from functools import reduce
import jwt
from django.conf import settings
import redis
from django.core.paginator import Paginator

# Create your views here.

# 轮播图的视图类
class CarouselAPIView(APIView):

    def get(self,request):
        # 查询所有的轮播图数据，返回给前端
        # 轮播图的模型类
        carousel_queryset = Carousel.objects.all()
        carousel_queryset_ser = CarouselSer(carousel_queryset,many=True)

        return Response({'code':200, "msg":"获取轮播图成功",
                         "carousel":carousel_queryset_ser.data})

# 加载一个类的商品数据
class OneCategoryGoods(APIView):
    def get(self,request):
#         1.获取前端类别
        cate_name = request.query_params.get("categoryName")
#         2.根据类别名   查询类别对象
        try:
            cate_obj = GoodCategory.objects.get(cate_name=cate_name)
        except:
            return Response({"code":204, "msg":"该类别不存在"})
#         3.由类别对象  反向查询该类的所有商品
        goods_queryset = cate_obj.good_set.all()
        goods_queryset_ser = GoodSer(goods_queryset,many=True)
        return Response(goods_queryset_ser.data)

# 热门商品
class HotProduct(APIView):
    def get(self,request):
        # 1.获取商品类别
        # print("查看类别:", request.query_params)
        cate_list = request.query_params.getlist("categoryName[]")

        print("类别:", cate_list)

        # 2.根据每一个类别名字，查询商品类别对象
        cate_obj_list = [GoodCategory.objects.get(cate_name=i) for i in cate_list]

        # 3.根据每一个类别对象,反向查询其对应的所有商品
        good_queryset_list = [i.good_set.all() for i in cate_obj_list]

        # 4.将所有的商品集合，进行 并的 操作
        # temp = set()
        # for i in good_queryset_list:
        #     temp |= i

        goods_queryset = reduce(lambda x,y: x|y, good_queryset_list).order_by('-count')

        # 5.将所有商品进行序列化
        goods_queryset_ser = GoodSer(goods_queryset, many=True)

        return Response(goods_queryset_ser.data)

# 商品详情

class GoodDetail(APIView):
    def get(self,request):

#         1.接收商品id
        good_id = request.query_params.get("productID")

#         2.根据商品id 查询商品对象
        try:
            good = Good.objects.get(id=good_id)
        except:
            return Response({"code":204, "msg":"商品不存在"})

#         3.序列化
        good_ser = GoodSer(good)
        return Response(good_ser.data)


# 详情轮播图
class DetailCarousel(APIView):
    def get(self,request):
        # 1.获取前端数据，商品id
        good_id = request.query_params.get("productID")
        # 2.查询商品对象
        try:
            good = Good.objects.get(id=good_id)
        except:
            return Response({"code":204, "msg":"商品不存在"})

        # 3.根据商品对象，反向查询其所有图片对象
        imgs_queryset = good.goodimg_set.all()

        # 4.对所有的图片对象，进行序列化
        imgs_queryset_set = GoodImgSer(imgs_queryset,many=True)

        return Response(imgs_queryset_set.data)


# 添加历史记录

class GoodHistory(APIView):
    def post(self,request):

        # 1.获取前端数据
        good_id = request.data.get("productID")
        token = request.data.get("token")

        # 2.根据token的值做相应的操作
        if not token:   # 没有token
            return Response({"code":203, "msg":"没有token"})

        # 3.有token，需要对token进行解码
        try:
            payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms="HS256")
        except:
            return Response({"code":204, "msg":"token解码错误"})

        # 4.解析出payload
        username = payload.get("username")

        # 5.构造key
        key = "history:%s"%username

        # 6.操作Redis 存储历史记录
        redis_conn = redis.Redis(host='localhost', port=6379, db=0, password=123)

        # 列表的删除、添加、截取
        redis_conn.lrem(key, 0, good_id)
        redis_conn.lpush(key, good_id)
        redis_conn.ltrim(key, 0, 4)
        redis_conn.close()

        return Response({"code":200, "msg":"添加历史记录成功"})

# 加载所有的商品类别
class CategoryAPIView(APIView):
    def get(self,request):
        # 1. 查询所有的类别对象
        cate_queryset = GoodCategory.objects.all()
        # 2. 序列化所有的类别对象
        cate_queryset_ser = GoodCategorySer(cate_queryset,many=True)
        return Response({"code":200, "msg":"获取类别成功", "category":cate_queryset_ser.data})

# 加载所有的商品
class GoodAPIView(APIView):
    def get(self,request):

        # 1.接收前端数据，便于实现所有商品的分页效果
        current_page = request.query_params.get("currentPage")
        page_size = request.query_params.get("pageSize")
        # 2.查询所有的商品对象
        goods_queryset = Good.objects.all()

        # 在第二步，增加商品的分页实现
        paginator = Paginator(goods_queryset,page_size)
        # 获取当前页面对象
        page = paginator.page(current_page)

        # 3.序列化所有的商品对象
        goods_queryset_ser = GoodSer(page.object_list,many=True)

        return Response({"code":200, "msg":"加载所有商品成功", "product":goods_queryset_ser.data,
                         "total":goods_queryset.count()})


# 加载指定类别的商品
class GoodByCategory(APIView):
    def get(self,request):
        # 1.接收前端数据
        cate_id = request.query_params.get("categoryID[]")
        current_page = request.query_params.get("currentPage")
        page_size = request.query_params.get("pageSize")

        # 2.根据种类id  查询种类对象
        cate = GoodCategory.objects.get(id=cate_id)

        # 3.通过种类对象，反向查询该类的所有商品
        goods_queryset = cate.good_set.all()
        paginator = Paginator(goods_queryset,page_size)
        page = paginator.page(current_page)

        # 4.序列化所有商品对象
        goods_queryset_ser = GoodSer(page.object_list,many=True)

        return Response({"code":200, "msg":"获取指定类别的商品成功", "product":goods_queryset_ser.data,
                         "total":goods_queryset.count()})

